from appium.webdriver.webdriver import WebDriver
from selenium.common import TimeoutException, NoSuchElementException
from selenium.webdriver.support import expected_conditions
from selenium.wendriver.support.wait import WebDriverWait

class BasePage:
    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    # 显式等待
    def find(self, by, value, timeout = 10):
        try:
            WebDriverWait(self.driver, timeout).until(expected_conditions.visibility_of_element_located((by, value)))
        except TimeoutException:
            raise NoSuchElementException(f"{(by, value)}元素未找到")
        except Exception as e:
            raise RuntimeError(f"{(by, value)}元素定位失败, {e}")
        return self.driver.find_element(by, value)

    # 返回元素列表，超时未找到才会返回空列表
    def finds(self, by, value, timeout = 5):
        try:
            WebDriverWait(self.driver, timeout).until(expected_conditions.visibility_of_element_located((by, value)))
        except TimeoutException:
            retrun []
        return self.driver.find_elements(by, value)

    # 获取屏幕大小
    def get_screen_size(self):
        return self.driver.get_window_size()

    # 上滑
    def swipe_up(self, t=500):
        screen_size = self.get_screen_size()
        x1 = screen_size['width'] * 0.5
        y1 = screen_size['height'] * 0.75
        y2 = screen_size['height'] * 0.25
        self.driver.swipe(x1, y1, x1, y2, t)

    # 下滑
    def swipe_down(self, t=500):
        screen_size = self.get_screen_size()
        x1 = screen_size['width'] * 0.5
        y1 = screen_size['height'] * 0.25
        y2 = screen_size['height'] * 0.75
        self.driver.swipe(x1, y1, x1, y2, t)

    # 左滑
    def swipe_left(self, t=500):
        screen_size = self.get_screen_size()
        x1 = screen_size['width'] * 0.75
        y1 = screen_size['height'] * 0.5
        x2 = screen_size['width'] * 0.25
        self.driver.swipe(x1, y1, x2, y1, t)

    # 右滑
    def swipe_right(self, t=500):
        screen_size = self.get_screen_size()
        x1 = screen_size['width'] * 0.25
        y1 = screen_size['height'] * 0.5
        x2 = screen_size['width'] * 0.75
        self.driver.swipe(x1, y1, x2, y1, t)